/*************************************************************************
	> File Name: mysqldemo.cpp
	> Author: 
	> Mail: 
	> Created Time: Mon Oct 19 10:39:38 2020
 ************************************************************************/

#include <iostream>
#include <string>
#include <mysql/mysql.h>
using namespace std;

class MysqlDB {
    private:
        MYSQL mysql;
        MYSQL_ROW row;
        MYSQL_RES *result;
        MYSQL_FIELD *field;
    public:
    MysqlDB() 
    {
        if( mysql_init( &mysql  ) == NULL  ) 
        {
                cout << "init error, line: " << __LINE__ << endl;
                exit(-1);
                    
        }
            
    }
        
    ~MysqlDB() 
    {
            mysql_close( &mysql  );
            
    }
        
    void connect( string host, string user, string passwd,  string database  ) 
    {
        if( !mysql_real_connect( &mysql, host.c_str(), user.c_str(), passwd.c_str(), database.c_str(), 0, NULL, 0  )  ) 
        {
                cout << "connect error, line: " << __LINE__ << endl;
                exit(-1);
                    
        }
            
    }
        
        void add();
        void print();

};

void MysqlDB::add() 
{
        string id, name, sex, birthday;
    do {
                cout << "请输入学生信息:\n";

                cin >> id >> name >> sex >> birthday;
                string sql = "insert into info values('" + id + "', '" + name + 
                                "', '" + sex + "', '" + birthday + "');";
        
                mysql_query( &mysql, sql.c_str()  );
                cout << "是否继续（y/n）: ";
                cin >> id;
            } while( id == "y"  );
}

void MysqlDB::print() 
{
    string sql = "select * from info;";
    mysql_query( &mysql, sql.c_str()  );

    result = mysql_store_result( &mysql  );
    if( !result  ) 
    {
        cout << "result error, line : " << __LINE__ << endl;
        return ;
            
    }

    int num = mysql_num_fields( result  );  //返回字段个数
    for( int i = 0; i < num; i++  ) {
        field = mysql_fetch_field_direct( result, i  );  //返回字段类型
        cout << field->name << "\t\t";  //输出字段名     
    }
    cout << endl;

    while( row = mysql_fetch_row( result  ), row  ) 
    {
        for( int i = 0; i < num; i++  ) 
        {
            cout << row[i] << "\t\t";
                    
        }
            cout << endl;
            
    }
}

int main() 
{
        MysqlDB db;
        db.connect( "localhost", "root","", "student"  ); 

        db.print();
        db.add();
        db.print();

        return 0;

}
